package cpustresser;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class CpuStress {

	private int timeout;
	
	private class Runner extends Thread {

		private int id;
		private int counter = 0;

		public Runner(int id) {
			this.id = id;
			setPriority(MIN_PRIORITY);
		}

		@Override
		public void run() {
			super.run();
			while (!interrupted()) {
				counter++;
			}
			System.out.println("Thread (id=" + id + "):" + counter);
		}
	}
	
	private static class Gui extends JFrame{
		
		private JTextField txtTimeout;
		private JTextField txtThreads;
		private JButton btnStart;
		private Gui me = this;
		
		public Gui(){
			super("Cpu Stresser");
			
			txtTimeout = new JTextField("60000");
			txtThreads = new JTextField("32");
			btnStart = new JButton("Start");
			btnStart.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					try{
						int timeout = Integer.parseInt(txtTimeout.getText());
						int threads = Integer.parseInt(txtThreads.getText());
						CpuStress cpuStress = new CpuStress(timeout);
						cpuStress.stress(threads);
					} catch (Exception ex ){
						JOptionPane.showMessageDialog(me, "Korrigieren Sie Ihre Eingaben.");
					}
				}
			});
			
			
			setLayout(new GridLayout(3,1));
			add(new JLabel("Zeit(ms):"));
			add(txtTimeout);
			add(new JLabel("Anzahl Threads:"));
			add(txtThreads);
			add(new JLabel(""));
			add(btnStart);
			
			setDefaultCloseOperation(EXIT_ON_CLOSE);
			pack();
		}
	}
	
	public CpuStress(int timeout){
		if (timeout < 1) {
			throw new IllegalArgumentException(
					"Timeout must be at minimum one milisecond");
		}
		this.timeout = timeout;
	}

	public void stress(int threads) {
		if (threads < 1) {
			throw new IllegalArgumentException(
					"There must be at minimum one Thread");
		}
		List<Runner> runners = new ArrayList<Runner>();
		for (int i = 0; i < threads; i++) {
			runners.add(new Runner(i+1));
		}
		for (Runner r : runners) {
			r.start();
		}
		try {
			Thread.sleep(timeout);
		} catch (InterruptedException e) {
		}
		for (Runner r : runners) {
			r.interrupt();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new Gui().setVisible(true);
	}
}
